import { ListVO, saveUser } from '../services';
import { Dialog, Field, Form, Input, Select, Switch } from '@alifd/next';
import { useEffect } from 'react';
import { useRequest } from 'ice';

interface Props {
  visible?: boolean;
  onClose?: () => any;
  onRefresh?: () => any;
  record?: ListVO;
}

const { Item: FormItem } = Form;

const formItemLayout = {
  labelCol: {
    fixedSpan: 6,
  },
  wrapperCol: {
    span: 16,
  },
};

function EditDialog({ visible, onClose, record, onRefresh }: Props) {
  const form = Field.useField([{}]);
  const { loading, request } = useRequest<string, ListVO[]>(saveUser, {
    defaultParams: [{}],
    debounceInterval: 300,
    onSuccess: () => {
      onClose?.();
      onRefresh?.();
    },
  });

  useEffect(() => {
    if (visible) {
      if (record) {
        form.setValues(record);
      }
    }
  }, [visible]);

  const onSubmit = () => {
    form.validateCallback((errors: any[], values: any) => {
      if (errors) {
        return;
      }
      request({ ...values });
    });
  };

  return (
    <Dialog
      title={record?.id ? '编辑账号' : '新增账号'}
      v2
      visible={visible}
      overflowScroll
      width="50%"
      onOk={onSubmit}
      onClose={onClose}
      afterClose={() => form.reset()}
      okProps={{ loading }}
      cancelProps={{ loading }}
    >
      <Form {...formItemLayout} disabled={loading} field={form} fullWidth colon useLabelForErrorMessage>
        <FormItem name="id" label="id" style={{ display: 'none' }}>
          <Input />
        </FormItem>
        <FormItem name="name" label="名称" required>
          <Input placeholder="请输入名称" />
        </FormItem>
        <FormItem name="email" label="邮箱" required format="email">
          <Input placeholder="请输入邮箱地址" />
        </FormItem>
        <FormItem name="password" disabled={!!record?.id} label="密码" required>
          <Input.Password placeholder="请输入密码" />
        </FormItem>
      </Form>
    </Dialog>
  );
}

export default EditDialog;
